package monitor

import (
	"sync"
	"sync/atomic"
	"time"
)

// PerformanceStats 性能统计
type PerformanceStats struct {
	ConnectionsActive   int64         // 活跃连接数
	ConnectionsTotal    int64         // 总连接数
	MessagesReceived    int64         // 接收消息数
	MessagesSent        int64         // 发送消息数
	BytesReceived       int64         // 接收字节数
	BytesSent          int64         // 发送字节数
	ErrorsTotal        int64         // 总错误数
	LastUpdateTime     time.Time     // 最后更新时间
	mu                 sync.RWMutex
}

// PerformanceMonitor 性能监控器
type PerformanceMonitor struct {
	stats      *PerformanceStats
	startTime  time.Time
	sampleRate time.Duration
	stopChan   chan struct{}
}

// NewPerformanceMonitor 创建性能监控器
func NewPerformanceMonitor(sampleRate time.Duration) *PerformanceMonitor {
	return &PerformanceMonitor{
		stats:      &PerformanceStats{},
		startTime:  time.Now(),
		sampleRate: sampleRate,
		stopChan:   make(chan struct{}),
	}
}

// Start 启动性能监控
func (pm *PerformanceMonitor) Start() {
	go pm.collectStats()
}

// Stop 停止性能监控
func (pm *PerformanceMonitor) Stop() {
	close(pm.stopChan)
}

// IncrementConnections 增加连接数
func (pm *PerformanceMonitor) IncrementConnections() {
	atomic.AddInt64(&pm.stats.ConnectionsActive, 1)
	atomic.AddInt64(&pm.stats.ConnectionsTotal, 1)
}

// DecrementConnections 减少连接数
func (pm *PerformanceMonitor) DecrementConnections() {
	atomic.AddInt64(&pm.stats.ConnectionsActive, -1)
}

// AddMessageReceived 增加接收消息统计
func (pm *PerformanceMonitor) AddMessageReceived(bytes int64) {
	atomic.AddInt64(&pm.stats.MessagesReceived, 1)
	atomic.AddInt64(&pm.stats.BytesReceived, bytes)
}

// AddMessageSent 增加发送消息统计
func (pm *PerformanceMonitor) AddMessageSent(bytes int64) {
	atomic.AddInt64(&pm.stats.MessagesSent, 1)
	atomic.AddInt64(&pm.stats.BytesSent, bytes)
}

// AddError 增加错误统计
func (pm *PerformanceMonitor) AddError() {
	atomic.AddInt64(&pm.stats.ErrorsTotal, 1)
}

// GetStats 获取性能统计
func (pm *PerformanceMonitor) GetStats() PerformanceStats {
	pm.stats.mu.RLock()
	defer pm.stats.mu.RUnlock()

	return PerformanceStats{
		ConnectionsActive: atomic.LoadInt64(&pm.stats.ConnectionsActive),
		ConnectionsTotal:  atomic.LoadInt64(&pm.stats.ConnectionsTotal),
		MessagesReceived:  atomic.LoadInt64(&pm.stats.MessagesReceived),
		MessagesSent:      atomic.LoadInt64(&pm.stats.MessagesSent),
		BytesReceived:     atomic.LoadInt64(&pm.stats.BytesReceived),
		BytesSent:        atomic.LoadInt64(&pm.stats.BytesSent),
		ErrorsTotal:      atomic.LoadInt64(&pm.stats.ErrorsTotal),
		LastUpdateTime:   pm.stats.LastUpdateTime,
	}
}

// GetUptime 获取运行时间
func (pm *PerformanceMonitor) GetUptime() time.Duration {
	return time.Since(pm.startTime)
}

// GetQPS 获取每秒查询率
func (pm *PerformanceMonitor) GetQPS() float64 {
	uptime := pm.GetUptime().Seconds()
	if uptime == 0 {
		return 0
	}
	stats := pm.GetStats()
	return float64(stats.MessagesReceived+stats.MessagesSent) / uptime
}

// GetThroughput 获取吞吐量（字节/秒）
func (pm *PerformanceMonitor) GetThroughput() float64 {
	uptime := pm.GetUptime().Seconds()
	if uptime == 0 {
		return 0
	}
	stats := pm.GetStats()
	return float64(stats.BytesReceived+stats.BytesSent) / uptime
}

// collectStats 收集统计信息
func (pm *PerformanceMonitor) collectStats() {
	ticker := time.NewTicker(pm.sampleRate)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			pm.stats.mu.Lock()
			pm.stats.LastUpdateTime = time.Now()
			pm.stats.mu.Unlock()
		case <-pm.stopChan:
			return
		}
	}
}

// SimpleMonitor 简化监控接口
type SimpleMonitor interface {
	IncrementConnections()
	DecrementConnections()
	AddMessageReceived(bytes int64)
	AddMessageSent(bytes int64)
	AddError()
}

// NoopMonitor 空操作监控器（用于测试）
type NoopMonitor struct{}

func (nm *NoopMonitor) IncrementConnections() {}
func (nm *NoopMonitor) DecrementConnections() {}
func (nm *NoopMonitor) AddMessageReceived(bytes int64) {}
func (nm *NoopMonitor) AddMessageSent(bytes int64) {}
func (nm *NoopMonitor) AddError() {}